﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using Microsoft.Win32;
using System.Collections;

namespace Spider
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
            httpHelper = new HttpHelper();
        }
        private Thread getPicThread;
        HttpHelper httpHelper;
        private delegate void DGetPic(Stream s);

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (this.txtUrl.Text.Trim().Length < 1)
            {
                MessageBox.Show("网站地址必填！");
            }
            SpiderAccount.Url = this.txtUrl.Text.Trim();
            SpiderAccount.CurrentAccount = this.txtUserName.Text.Trim();
            SpiderAccount.CurrentPwd = this.txtPwd.Text.Trim();

            #region 登录，并取得cookie

            #region 以前的Post字符串，现在没用了
            string str = string.Empty;
            str += "username=" + this.txtUserName.Text;
            str += "&password=" + this.txtPwd.Text;
            str += "&authcode=" + this.txtVerifyCode.Text.Trim();
            str += "&opt_password=";
            str += "&agreerule=Y";
            str += "&pid=2";
            str += "&goto_cs=0";
            str += "&refer=http://gs.gm.163.com/index.html";
            #endregion

            string html = httpHelper.GetHtml(this.txtPostUrl.Text, this.txtPostStr.Text, true, CookieMng.CurrentCookie);
            string success = string.Empty;

            success = html;

            if (string.IsNullOrEmpty(success))
            {
                MessageBox.Show("登录失败，请重试！");
                getPicThread = new Thread(new ThreadStart(GetPicRunInThread));
                getPicThread.IsBackground = true;
                getPicThread.Start();
                return;
            }
            else
            {
                this.DialogResult = DialogResult.OK;
            }
            #endregion

            Log.WriteLog("账户:" + SpiderAccount.CurrentAccount + "在" + DateTime.Now.ToString() + "成功登录！");

            AppConfiguration.SetConfiguration("url", SpiderAccount.Url);
            AppConfiguration.SetConfiguration("loginname", this.txtUserName.Text.Trim());
            AppConfiguration.SetConfiguration("loginpwd", this.txtPwd.Text);
            AppConfiguration.SetConfiguration("validatecodeurl", this.txtValidateUrl.Text.Trim());
            AppConfiguration.SetConfiguration("posturl", this.txtPostUrl.Text.Trim());
            AppConfiguration.SetConfiguration("poststr", this.txtPostStr.Text.Trim());

            #region 注册表保存登录的账号
            //string account = "Software\\Heiyr\\Settings\\Spider";
            //RegistryKey userkey = Registry.CurrentUser.OpenSubKey(account, true);
            //userkey = Registry.CurrentUser.CreateSubKey(account, RegistryKeyPermissionCheck.ReadWriteSubTree);
            //userkey.SetValue("user", SpiderAccount.CurrentAccount);
            //userkey.Close();

            //RegistryKey userpwdkey = Registry.CurrentUser.OpenSubKey(account, true);
            //userpwdkey = Registry.CurrentUser.CreateSubKey(account, RegistryKeyPermissionCheck.ReadWriteSubTree);
            //userpwdkey.SetValue("userpwd", SpiderAccount.CurrentPwd);
            //userpwdkey.Close();
            #endregion
        }

        private void btnGetCode_Click(object sender, EventArgs e)
        {
            getPicThread = new Thread(new ThreadStart(GetPicRunInThread));
            getPicThread.IsBackground = true;
            getPicThread.Start();
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            //string sssssssss = "index_1.html";
            //System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"_[0-9]{1,2}\.html");
            //if (regex.IsMatch(sssssssss))
            //{
            //    MessageBox.Show("true");
            //}

            Thread.CurrentThread.IsBackground = true;
            Utility.DeleteTemp();
            #region 绑定模板列表
            new CompData().BindTemplate(this.cmboxTemplateList);
            #endregion
            ShowListUrl();

            //this.txtUserName.Text = AppConfiguration.GetConfiguration("loginname");
            //this.txtPwd.Text = AppConfiguration.GetConfiguration("loginpwd");
            //this.txtValidateUrl.Text = AppConfiguration.GetConfiguration("validatecodeurl");
            //this.txtPostUrl.Text = AppConfiguration.GetConfiguration("posturl");
            //this.txtPostStr.Text = AppConfiguration.GetConfiguration("poststr");

            //this.txtPostUrl.Text = "http://bbs.shoeshr.com/logging.php?action=login";
            //this.txtPostStr.Text = "formhash=dbf2e9b7&referer=http://bbs.shoeshr.com/registers.php&loginfield=username&username=lhking&password=lhking&questionid=0&answer=&cookietime=2592000&loginmode=&styleid=&loginsubmit=true";

            #region 载入注册表里的默认账号
            //string account = "Software\\Heiyr\\Settings\\Spider";
            //RegistryKey userkey = Registry.CurrentUser.OpenSubKey(account, true);
            //if (userkey != null)
            //{
            //    this.txtUserName.Text = (string)userkey.GetValue("user");
            //}
            //RegistryKey userpwdkey = Registry.CurrentUser.OpenSubKey(account, true);
            //if (userpwdkey != null)
            //{
            //    this.txtPwd.Text = (string)userpwdkey.GetValue("userpwd");
            //}
            #endregion

            this.AcceptButton = this.btnLogin;
        }

        #region 获取登录验证码
        private void GetPicRunInThread()
        {
            Stream s = new Utility().GetValidateCode(this.txtValidateUrl.Text.Trim());
            DGetPic dgetpic = new DGetPic(getPic);
            this.BeginInvoke(dgetpic, s);
        }
        /// <summary>
        /// 得到验证码图片
        /// </summary>
        private void getPic(Stream s)
        {
            try
            {
                if (s == null)
                {
                    MessageBox.Show("本程序获取登陆验证码错误，请检查您的网络!", "提示信息");
                    return;
                }
                this.picboxVerifyCode.Image = Image.FromStream(s);
                s.Close();
                this.txtVerifyCode.Text = "";
            }
            catch
            {
                MessageBox.Show("本程序获取登陆验证码错误，请检查您的网络!", "提示信息");
                return;
            }
        }
        #endregion

        private void picboxVerifyCode_Click(object sender, EventArgs e)
        {
            getPicThread = new Thread(new ThreadStart(GetPicRunInThread));
            getPicThread.IsBackground = true;
            getPicThread.Start();
        }

        private void btnDirectLogin_Click(object sender, EventArgs e)
        {
            if (this.txtUrl.Text.Trim().Length < 1)
            {
                MessageBox.Show("网站地址必填！");
            }
            SpiderAccount.Url = this.txtUrl.Text.Trim();
            SpiderAccount.TemplateId = this.cmboxTemplateList.SelectedValue.ToString();
            AppConfiguration.SetConfiguration("url", SpiderAccount.Url);

            this.DialogResult = DialogResult.OK;
        }

        private void gboxValidateCode_Enter(object sender, EventArgs e)
        {

        }

        private void cmboxTemplateList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowListUrl();
        }
        private void ShowListUrl()
        {
            try
            {
                Hashtable ht = new CompData().GetTemplateData(this.cmboxTemplateList.SelectedValue.ToString());
                this.txtUrl.Text = ht["url"].ToString();
            }
            catch
            {
            }
        }
    }
}
